package com.stone.stoneanswer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stone.stoneanswer.common.ErrorCode;
import com.stone.stoneanswer.exception.BusinessException;
import com.stone.stoneanswer.model.dto.comment.CommentAddRequest;
import com.stone.stoneanswer.model.entity.CommentThumb;
import com.stone.stoneanswer.model.entity.Comment;
import com.stone.stoneanswer.model.entity.User;
import com.stone.stoneanswer.model.vo.CommentVO;
import com.stone.stoneanswer.service.CommentThumbService;
import com.stone.stoneanswer.mapper.CommentMapper;
import com.stone.stoneanswer.service.UserService;
import org.springframework.stereotype.Service;
import com.stone.stoneanswer.service.CommentService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 35431
 * @description 针对表【post_comment(评论表)】的数据库操作Service实现
 * @createDate 2025-03-27 10:02:50
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
        implements CommentService {

    @Resource
    UserService userService;

    @Resource
    CommentThumbService commentThumbService;


    @Override
    public List<CommentVO> getCommentByTypeAndId(Long itemId, Integer itemType, HttpServletRequest request) {
        List<Comment> commentList = this.list(new QueryWrapper<Comment>().lambda()
                .eq(Comment::getItemId, itemId)
                .eq(Comment::getItemType, itemType)
                .orderByDesc(Comment::getCreateTime));
        Map<Long, CommentVO> commentVOMap = new HashMap<>();
        for (Comment comment : commentList) {
            CommentVO commentVO = CommentVO.objToVo(comment);
            User user = userService.getById(comment.getUserId());
            commentVO.setUserAvatar(user.getUserAvatar());
            commentVO.setUserName(user.getUserName());
            if (comment.getToUserId() != null && comment.getToUserId() > 0) {
                User toUser = userService.getById(comment.getToUserId());
                commentVO.setToUserName(toUser.getUserName());
                commentVO.setToUserAvatar(toUser.getUserAvatar());
            }

            // 查询评论点赞表，判断当前用户是否点赞了某个评论
            // 先获取当前登录的用户ID
            Long userId = userService.getLoginUser(request).getId();
            CommentThumb commentThumb = commentThumbService.getOne(new QueryWrapper<CommentThumb>().lambda().eq(CommentThumb::getCommentId, comment.getId())
                    .eq(CommentThumb::getUserId, userId));
            commentVO.setHasThumb(commentThumb != null);
            commentVOMap.put(commentVO.getId(), commentVO);
        }
        List<CommentVO> result = new ArrayList<>();
        for (Comment comment : commentList) {
            if (comment.getParentId() != null && comment.getParentId() > 0) {
                CommentVO commentVO = commentVOMap.get(comment.getParentId());
                commentVO.getReplies().add(commentVOMap.get(comment.getId()));
            } else {
                result.add(commentVOMap.get(comment.getId()));
            }
        }
        return result;
    }

    @Override
    public Long addComment(CommentAddRequest commentAddRequest,Integer itemType, HttpServletRequest request) {
        Long itemId = commentAddRequest.getItemId();
        String content = commentAddRequest.getContent();
        Long toUserId = commentAddRequest.getToUserId();
        Long parentId = commentAddRequest.getParentId();

        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();

        Comment comment = new Comment();
        comment.setItemId(itemId);
        comment.setItemType(itemType);
        comment.setContent(content);
        comment.setUserId(userId);
        comment.setToUserId(toUserId);
        comment.setThumbNum(0);
        comment.setParentId(parentId);

        save(comment);
        return comment.getId();
    }

    @Override
    public int doCommentThumb(Long commentId, User loginUser) {
        // 判断实体是否存在
        Comment comment = this.getById(commentId);
        if (comment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 查询是否已经点赞
        long userId = loginUser.getId();
        QueryWrapper<CommentThumb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("commentId", commentId);
        queryWrapper.eq("userId", userId);
        CommentThumb commentThumb = commentThumbService.getOne(queryWrapper);
        // 判断是否已经点赞
        if (commentThumb != null) {
            // 已经点赞，将点赞数减少1
            commentThumbService.remove(queryWrapper);
            this.update()
                    .eq("id", commentId)
                    .gt("thumbNum", 0)
                    .set("thumbNum", comment.getThumbNum() - 1)
                    .update();
            return -1;
        } else {
            // 没有点赞，将点赞数增加1
            commentThumb = new CommentThumb();
            commentThumb.setCommentId(commentId);
            commentThumb.setUserId(userId);
            commentThumbService.save(commentThumb);
            this.update()
                    .eq("id", commentId)
                    .set("thumbNum", comment.getThumbNum() + 1)
                    .update();
            return 1;
        }
    }
}




